<template>
  <div class="container">
    <div class="topInfo">
      <topTitle :titleText="titleText"></topTitle>
      <div class="subTitle" v-if="actionType === 'detail'">
        <el-button
          v-if="isShowUpdate"
          icon="icon iconfont iconbianji"
          class="commonBut saveBtn funComBut"
          @click="updateScore"
        >
          <span class="opetareText">编辑</span>
        </el-button>
        <span class="setInfo" style="float: right; margin-right: 20px"
          >上次保存时间：{{ updateTime || '--' }}</span
        >
      </div>
    </div>
    <div class="mainCon">
      <div v-if="actionType === 'detail'" class="normal-table">
        <el-table
          :data="tableList"
          v-loading="loading"
          :header-cell-style="{ background: '#eef1f6', color: '#606266' }"
          highlight-current-row
          stripe
          border
          :span-method="objectSpanMethod"
        >
          <el-table-column
            prop="clsName"
            label="指标类别"
            align="center"
            :formatter="formatTd"
            min-width="30%"
          ></el-table-column>
          <el-table-column
            prop="itemName"
            label="指标名称"
            align="center"
            :formatter="formatTd"
            min-width="30%"
          ></el-table-column>
          <el-table-column
            prop="score"
            label="指标分值"
            align="center"
            :formatter="formatTd"
            min-width="30%"
          ></el-table-column>
          <!-- 表格数据为空时，页面显示 -->
          <div slot="empty" v-show="isShow">
            <emptyTable emptyText="暂无相关数据"></emptyTable>
          </div>
        </el-table>
      </div>
      <div v-if="actionType === 'edit'" class="form-table">
        <el-form :model="formData" :rules="rules" ref="scoreForm">
          <el-table
            :data="tableList"
            v-loading="loading"
            :header-cell-style="{ background: '#eef1f6', color: '#606266' }"
            highlight-current-row
            stripe
            border
            :span-method="objectSpanMethod"
          >
            <el-table-column
              prop="clsName"
              label="指标类别"
              align="center"
              :formatter="formatTd"
              min-width="30%"
            ></el-table-column>
            <el-table-column
              prop="itemName"
              label="指标名称"
              align="center"
              :formatter="formatTd"
              min-width="30%"
            ></el-table-column>
            <!-- <el-table-column v-if="actionType === 'detail'" prop="score" label="指标分值" align="center" :formatter="formatTd" min-width="30%"></el-table-column> -->
            <el-table-column
              label="指标分值"
              align="center"
              :formatter="formatTd"
              min-width="30%"
            >
              <template slot-scope="scope">
                <el-form-item
                  :prop="'scoreList.' + scope.$index + '.score'"
                  :rules="rules.score"
                  style="margin-top: 22px; padding: 0 30px"
                  label-width="0"
                >
                  <el-input
                    v-model="formData['scoreList'][scope.$index].score"
                  ></el-input>
                </el-form-item>
              </template>
            </el-table-column>
            <!-- 表格数据为空时，页面显示 -->
            <div slot="empty" v-show="isShow">
              <emptyTable emptyText="暂无相关数据"></emptyTable>
            </div>
          </el-table>
        </el-form>
        <div style="text-align: center">
          <el-button
            class="commonBut saveBtn saveScore"
            @click.native="saveScore('scoreForm')"
            >保存</el-button
          >
        </div>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  name: 'IndexScoreAllocation',
  data() {
    var validateScore = (rule, value, callback) => {
      let reg = /^(([1-9]\d*)(\.[0-9])?|0\.[0-9]|0)$/
      if (!value && value !== 0) {
        callback(new Error('请输入分值'))
      } else if (!reg.test(value)) {
        callback(new Error('分值需大于等于0，且支持小数点后1位'))
      } else if (value * 1 > 10000) {
        callback(new Error('分值需小于等于10000'))
      } else {
        callback()
      }
    }
    return {
      titleText: '指标分值配置',
      updateTime: '',
      tableList: [],
      formData: {
        scoreList: [],
      },
      rules: {
        score: [
          {
            required: true,
            message: '请输入指标分值',
            trigger: 'blur',
          },
          { validator: validateScore, trigger: 'blur' },
        ],
      },
      isShow: false,
      loading: false,
      actionType: 'detail',
      isShowUpdate: false,
    }
  },
  created() {
    this.getIndexScoreList()
    this.isShowUpdate =
      this.$store.state.buttonLimitsArr.indexOf('indexScoreAllocation:update') >
      -1
  },
  methods: {
    // 指标分值列表
    getIndexScoreList() {
      this.loading = true
      return this.axios({
        method: 'post',
        url: '/api-gov/govExamConfig/expand/listConfig',
      })
        .then((response) => {
          this.loading = false
          if (!response.data.hasError) {
            this.isShow = false
            const results = response.data.result
            this.tableList = results
            if (this.tableList.length < 1) {
              this.isShow = true
            }
            this.updateTime = this.tableList[0] && this.tableList[0].lastTime
          } else {
            this.isShow = true
            this.$message.error(response.data.errorMsg)
          }
        })
        .catch((error) => {
          this.loading = false
          this.isShow = true
          if (error.response) {
            this.$message.error(error.response.data)
          }
        })
    },
    updateScore() {
      this.formData.scoreList = JSON.parse(JSON.stringify(this.tableList))
      this.actionType = 'edit'
    },
    // 保存分值配置
    saveScore(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          return this.axios({
            method: 'post',
            url: '/api-gov/govExamConfig/expand/modify',
            data: {
              govExamConfigExpandVOS: JSON.stringify(this.formData.scoreList),
            },
          })
            .then((response) => {
              if (!response.data.hasError) {
                this.getIndexScoreList()
                this.actionType = 'detail'
              } else {
                this.$message.error(response.data.errorMsg)
              }
            })
            .catch((error) => {
              if (error.response) {
                this.$message.error(error.response.data)
              }
            })
        } else {
          this.$message.error('请按照提示规则输入内容!')
          return false
        }
      })
    },
    // 合并行
    objectSpanMethod({ row, column, rowIndex, columnIndex }) {
      if (columnIndex === 0) {
        const _row = this.mergeSpan(this.tableList).spanArr[rowIndex]
        const _col = _row > 0 ? 1 : 0
        return {
          rowspan: _row,
          colspan: _col,
        }
      }
    },
    // 合并行判断条件
    mergeSpan(tableData) {
      let spanArr = []
      let concat = 0
      tableData.forEach((item, index) => {
        if (index === 0) {
          spanArr.push(1)
        } else {
          if (item.classification === tableData[index - 1].classification) {
            //需合并相同内容的判断条件
            spanArr[concat]++
            spanArr.push(0)
          } else {
            spanArr.push(1)
            concat = index
          }
        }
      })
      return {
        spanArr,
      }
    },
  },
}
</script>

<style scoped lang="less">
.container {
  .topInfo {
    height: 50px;
    position: relative;
    .subTitle {
      width: 400px;
      height: 50px;
      line-height: 50px;
      position: absolute;
      right: 0;
      top: 0;
      padding-right: 24px;
      .setInfo {
        line-height: 50px;
        font-size: 14px;
        color: #4c4c4c;
      }
      /deep/ .el-button {
        height: 36px;
        // width: 70px;
        background: #009588;
        font-size: 14px;
        color: #ffffff;
        border: none;
        margin-top: 7px;
        float: right;
      }
    }
  }
  .mainCon {
    top: 196px;
    padding: 24px;
    .saveScore {
      width: 136px;
      background: #009588;
      font-size: 14px;
      color: #ffffff;
      margin: 40px auto;
      height: 36px;
    }
    .form-table {
      /deep/ .el-table td {
        padding: 0;
      }
      /deep/.el-table td > .cell {
        padding: 0 !important;
      }
    }
  }
}
</style>
